package com.idea.zd.sys.train.jms;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * 消息消费者
 */
public class Consumer {

    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
    private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
    private static final String BROKERURL = ActiveMQConnection.DEFAULT_BROKER_URL;

    //客户端用来创建连接的受管对象
    private ConnectionFactory connectionFactory;

    //客户端到JSM提供者之间活动连接
    private Connection connection;

    //发送和接收消息的一个单线程上下文
    private Session session;

    /**
     * 初始连接方法
     */
    public void init(){
        try {
            //工厂实现
            connectionFactory = new ActiveMQConnectionFactory(USERNAME,PASSWORD,BROKERURL);
            //创建jsm连接
            connection = connectionFactory.createConnection();
            //开启连接
            connection.start();
            //创建session
            session = connection.createSession(true,Session.AUTO_ACKNOWLEDGE);
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }

    public void getMessage(String disName){
        try {
            //创建对列
            Queue queue = session.createQueue(disName);
            //创建消费者
            MessageConsumer messageConsumer = session.createConsumer(queue);

            messageConsumer.setMessageListener(new MessageListener() {
                @Override
                public void onMessage(Message message) {
                    TextMessage textMessage = (TextMessage) message;


                    if(null != textMessage){
                        try {
                            //通知已接收
                            //textMessage.acknowledge();
                            session.commit();
                            System.out.println(textMessage.getText());
                        } catch (JMSException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });

            /*while(true){
                //接收的消息
                TextMessage textMessage = (TextMessage) messageConsumer.receive();
                //通知已接收
                textMessage.acknowledge();

                if(null != textMessage){
                    System.out.println(textMessage.getText());
                }else{
                    break;
                }
            }*/

        } catch (JMSException e) {
            e.printStackTrace();
        }finally {
            /*if(null !=connection){
                try {
                    connection.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }*/
        }
    }
}
